import type { FC } from 'react'
import { useMemo } from 'react'
import { Breadcrumb } from 'antd'
import { useLocation, matchPath, useAsyncValue } from 'react-router-dom'

type BreadcrumbItem = {
  title: string
}

const RootBreadcrumb: FC = () => {
  const location = useLocation()
  // 1. 获取当前的所处的地址
  const nowPathname = location.pathname === '/' ? '/home' : location.pathname
  const [result] = useAsyncValue() as [BaseResponse<MenuItem[]>, void]
  const items = useMemo(() => resolveBreadcrumbItems(result.data, nowPathname), [result.data, nowPathname])

  return <Breadcrumb items={items} />
}

const resolveBreadcrumbItems = (menus: MenuItem[] | undefined, selectedKey: string, breadcrumbItems: BreadcrumbItem[] = []) => {
  if (!menus) return
  for (const item of menus) {
    const matchResult = matchPath(item.key, selectedKey)
    if (matchResult) {
      // 成功匹配到了选中的菜单项
      breadcrumbItems.unshift({ title: item.label })
      return breadcrumbItems
    }

    if (item.children) {
      const result = resolveBreadcrumbItems(item.children, selectedKey, breadcrumbItems)
      if (result) {
        breadcrumbItems.unshift({ title: item.label })
        return breadcrumbItems
      }
    }
  }
}

export default RootBreadcrumb
